package com.immunology.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.immunology.model.Complaint;
import com.immunology.service.ComplaintService;

public class GetComplaintListBySyndromeId extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public GetComplaintListBySyndromeId() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int syndromeId = Integer.parseInt(request.getParameter("syndromeId"));
		Map<String, Map<String, List<Complaint>>> syndromeMap = null;
		Map<String, List<Complaint>> complaintTypeMap = null;

		ComplaintService complaintService = ComplaintService.getInstance();
		syndromeMap = complaintService.getComplaintListBySyndromeId(syndromeId);
		String syndromeName = syndromeMap.keySet().iterator().next();
		complaintTypeMap = syndromeMap.get(syndromeName);

		Iterator<String> complaintTypeIterator = complaintTypeMap.keySet()
				.iterator();

		JSONObject resultObject = new JSONObject();
		JSONArray complaintTypeObjectList = new JSONArray();
		JSONObject complaintObject = null;
		JSONArray complaintObjectList = null;

		while (complaintTypeIterator.hasNext()) {
			String complaintTypeName = complaintTypeIterator.next();

			complaintObjectList = new JSONArray();

			for (Complaint complaint : complaintTypeMap.get(complaintTypeName)) {
				complaintObject = new JSONObject();
				complaintObject.put("id", complaint.getId());
				complaintObject.put("name", complaint.getName());
				complaintObjectList.add(complaintObject);
			}

			JSONObject complaintTypeObject = new JSONObject();
			complaintTypeObject.put("name", complaintTypeName);
			complaintTypeObject.put("complaints", complaintObjectList);

			complaintTypeObjectList.add(complaintTypeObject);
		}

		resultObject.put("complaintTypes", complaintTypeObjectList);
		System.out.println(resultObject);

		getServletContext().setAttribute("syndromeId", syndromeId);
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(resultObject);
	}

}
